package com.woniuxy.third.utils;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.woniuxy.third.enums.TokenEnum;

/**
 * @Author: yangtao
 *
 * @date 2021/7/14 11:38 @Version 1.0
 */
public class JwtUtil {
  public static final String SECRET_KEY = "123456"; // 秘钥
  public static final long TOKEN_EXPIRE_TIME = 60 * 2 * 1000; // token过期时间
  public static final long REFRESH_TOKEN_EXPIRE_TIME = 60 * 60 * 1000*12; // refreshToken过期时间
  private static final String ISSUER = "yangtao"; // 签发人

  /** 生成签名 */
  public static String generateToken(String account) {
    Date now = new Date();
    // 创建签名算法对象
    Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); // 算法

    String token =
        JWT.create()
            .withIssuer(ISSUER) // 签发人
            .withIssuedAt(now) // 签发时间
            .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) // 过期时间
            .withClaim("account", account) // 保存身份标识
            .sign(algorithm);
    System.out.println(token);
    return token;
  }

  /** 验证token */
  public static TokenEnum verify(String token) {
    try {
      // 签名算法
      Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); // 算法
      JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
      verifier.verify(token);
      // 校验成功
      return TokenEnum.TOKEN_TRUE;
    } catch (TokenExpiredException ex) {
      // 过期
      return TokenEnum.TOKEN_EXPIRE;
    } catch (Exception ex) {
      // 验证失败
      return TokenEnum.TOKEN_FAIL;
    }
  }

  /** 从token获取uname */
  public static String getAccount(String token) {
    try {
      return JWT.decode(token).getClaim("account").asString();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return "";
  }
}
